﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//引入命名空间
using stwh_Model;
using stwh_BLL;
using stwh_Common;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.Web.SessionState;
using System.Web.Compilation;
using System.Xml;

namespace stwh_Web.Handler.stwh_admin
{
    public class BaseHandler : IHttpHandler, IRequiresSessionState
    {
        private static stwh_loginlogBLL loginlogbll = new stwh_loginlogBLL();

        /// <summary>
        /// 校验请求路径是否在白名单中（不需要验证的功能页面或handler）
        /// </summary>
        /// <param name="url">请求路径（相对路径）</param>
        /// <returns></returns>
        public static bool ChkURL(string url)
        {
            bool result = true;
            List<string> urllist = stwh_Web.stwh_admin.Common.WebSite.LoadChkURL();
            if (urllist.Where(a => a == url).ToList<string>().Count != 0) result = false;
            return result;
        }

        /// <summary>
        /// 校验是否登录,校验成功返回当前登陆用户对象
        /// </summary>
        /// <param name="context">数据上下文</param>
        public static stwh_userinfo IsCheckLogged(HttpContext context)
        {
            try
            {
                object user = null;
                if (context.Session == null || (user = context.Session["htuser"]) == null)
                {
                    context.Response.Redirect("/stwh_admin/invalid.htm");
                    return null;
                }
                return user as stwh_userinfo;
            }
            catch (Exception)
            {
                context.Response.Redirect("/stwh_admin/invalid.htm");
                return null;
            }
        }

        /// <summary>
        /// 添加操作日志信息
        /// </summary>
        /// <param name="remark"></param>
        public static void AddLog(string remark)
        {
            FileHelper.WriteError("error：" + remark + "");
            //判断是否开启操作日志记录
            if (stwh_Web.stwh_admin.Common.WebSite.LoadWebSite().Weblogs == 0)
            {
                stwh_loginlog loginlog = new stwh_loginlog();
                loginlog.stwh_lobrowse = GetClientInformation.GetClientBrowserVersions();
                loginlog.stwh_lodevice = GetClientInformation.GetClientSystemCheck();
                loginlog.stwh_loip = GetClientInformation.GetClientIP();
                try
                {
                    loginlog.stwh_loplace = GetClientInformation.GetClientPlace();
                }
                catch (Exception)
                {
                    loginlog.stwh_loplace = "未知";
                }
                loginlog.stwh_lotime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                try
                {
                    if (HttpContext.Current.Session["htuser"] == null) loginlog.stwh_loname = "未知";
                    else loginlog.stwh_loname = (HttpContext.Current.Session["htuser"] as stwh_userinfo).stwh_uiname;
                }
                catch (Exception)
                {
                    loginlog.stwh_loname = "未知";
                }
                loginlog.stwh_loremark = remark;
                loginlogbll.Add(loginlog);
            }
        }

        /// <summary>
        /// 添加资源
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filepath"></param>
        public static void AddResource(HttpContext context, string filepath)
        {
            string stwh_uiname = "未知";
            try
            {
                stwh_userinfo user = context.Session["htuser"] as stwh_userinfo;
                stwh_uiname = user.stwh_uiname;
            }
            catch (Exception)
            {
            }
            FileInfo fi = new FileInfo(context.Server.MapPath(filepath));
            stwh_Resources model = new stwh_Resources();
            model.stwh_readdtime = DateTime.Now;
            model.stwh_rename = fi.Name;
            model.stwh_repath = filepath;
            model.stwh_resize = Math.Ceiling((fi.Length / 1024.00)) + "KB";
            model.stwh_retime = fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
            model.stwh_retype = fi.Extension;
            model.stwh_reuname = stwh_uiname;
            new stwh_ResourcesBLL().Add(model);
        }

        /// <summary>
        /// 获取文章栏目（并判断一级栏目下是否有子栏目）
        /// </summary>
        /// <param name="datasource">数据源</param>
        /// <param name="listSave">储存</param>
        /// <param name="pid">父id</param>
        /// <param name="dj">栏目等级</param>
        public static void ArticleList(List<stwh_artype> datasource, StringBuilder listSave, int pid, int dj)
        {
            //筛选栏目
            List<stwh_artype> listadd = datasource.Where(aa => aa.stwh_artparentid == pid && aa.stwh_artid != pid).ToList<stwh_artype>();
            if (listadd.Count != 0)
            {
                //循环递归判断当前栏目下是否有子栏目
                foreach (stwh_artype item in listadd)
                {
                    listSave.Append(item.stwh_artid + ",");
                    ArticleList(datasource, listSave, item.stwh_artid, dj + 1);
                }
            }
        }

        /// <summary>
        /// 获取文章栏目（并判断一级栏目下是否有子栏目）
        /// </summary>
        /// <param name="datasource">数据源</param>
        /// <param name="listSave">储存</param>
        /// <param name="pid">父id</param>
        public static void ArticleList(List<stwh_artype> datasource, List<stwh_artype> listSave, int pid)
        {
            //筛选栏目
            List<stwh_artype> listadd = datasource.Where(aa => aa.stwh_artparentid == pid && aa.stwh_artid != pid).ToList<stwh_artype>();
            if (listadd.Count != 0)
            {
                //循环递归判断当前栏目下是否有子栏目
                foreach (stwh_artype item in listadd)
                {
                    listSave.Add(item);
                    ArticleList(datasource, listSave, item.stwh_artid);
                }
            }
        }

        /// <summary>
        /// 获取产品分类下的子分类
        /// </summary>
        /// <param name="datasource">数据源</param>
        /// <param name="listSave">储存</param>
        /// <param name="pid">父id</param>
        /// <param name="dj">栏目等级</param>
        public static void ProductTypeList(List<stwh_producttype> datasource, StringBuilder listSave, int pid, int dj)
        {
            //筛选栏目
            List<stwh_producttype> listadd = datasource.Where(aa => aa.stwh_ptparentid == pid && aa.stwh_ptid != pid).ToList<stwh_producttype>();
            if (listadd.Count != 0)
            {
                //循环递归判断当前栏目下是否有子栏目
                foreach (stwh_producttype item in listadd)
                {
                    listSave.Append(item.stwh_ptid + ",");
                    ProductTypeList(datasource, listSave, item.stwh_ptid, dj + 1);
                }
            }
        }

        /// <summary>
        /// 获取产品分类下的子分类
        /// </summary>
        /// <param name="datasource">数据源</param>
        /// <param name="listSave">储存</param>
        /// <param name="pid">父id</param>
        public static void ProductTypeList(List<stwh_producttype> datasource, List<stwh_producttype> listSave, int pid)
        {
            //筛选栏目
            List<stwh_producttype> listadd = datasource.Where(aa => aa.stwh_ptparentid == pid && aa.stwh_ptid != pid).ToList<stwh_producttype>();
            if (listadd.Count != 0)
            {
                //循环递归判断当前栏目下是否有子栏目
                foreach (stwh_producttype item in listadd)
                {
                    listSave.Add(item);
                    ProductTypeList(datasource, listSave, item.stwh_ptid);
                }
            }
        }

        /// <summary>
        /// 向客户端输出消息，消息格式为json格式
        /// </summary>
        /// <param name="context">数据上下文</param>
        /// <param name="msgcode">消息代码</param>
        /// <param name="msg">消息内容</param>
        /// <param name="sumcount">消息数量</param>
        public static void SendResponseMsgs(HttpContext context, string msgcode, object msg, int sumcount)
        {
            stwh_result result = new stwh_result();
            result.msgcode = msgcode;
            result.msg = msg;
            result.sumcount = sumcount;
            context.Response.Write(JsonConvert.SerializeObject(result));
            context.Response.Flush();
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                stwh_userinfo model = null;
                if (context.Session != null && context.Session["htuser"] != null)
                {
                    model = context.Session["htuser"] as stwh_userinfo;

                    #region 判断角色是否有权限访问具体功能栏目
                    //获取请求的虚拟路径
                    string url = context.Request.CurrentExecutionFilePath.ToLower();
                    string pathTranslated = context.Request.PhysicalPath;

                    string fString = Path.GetFileName(pathTranslated);
                    string[] arrayFile = fString.Split('.');
                    string[] arraypString = Path.GetDirectoryName(pathTranslated).Split('\\');
                    string pString = arraypString[arraypString.Length - 1];
                    if (BaseHandler.ChkURL(url))
                    {
                        if (model.stwh_uiid != 1 && !new stwh_roleinfoBLL().CheckRoleFunction(model.stwh_rid, pString, fString))
                        {
                            SendResponseMsgs(context, "-1", "您无权操作，请联系管理员！", 0);
                            return;
                        }
                    }
                    #endregion

                    Type handlerType = BuildManager.GetCompiledType(url);
                    // 采用动态反射机制创建相应的IHttpHandler实现类。
                    object obj = Activator.CreateInstance(handlerType, true);
                    IHttpHandler handler = (IHttpHandler)obj;
                    handler.ProcessRequest(context);
                }
                else
                {
                    SendResponseMsgs(context, "-1", "登录状态已失效，请重新登录！", 0);
                }
            }
            catch (Exception ex)
            {
                SendResponseMsgs(context, "-1", ex.Message, 0);
            }
        }
    }
}